<?php

/**
 * 对文件的各种处理
 *
 */
class File
{
	/**
	 * 附件类型及其所对应的扩展名
	 *
	 * @var array
	 */
	protected $imgExt = array('gif','jpg','jpeg','png');

	/**
	 * 属于视频类文件的扩展名
	 *
	 * @var array
	 */
	protected $videoExt = array('avi', 'rm', 'rmvb', '3gp', 'mp4', 'flv', 'wmv','mpg', 'mkv');
	protected $server;
	
	protected function __construct()
	{
		require_once(D_P . 'data/cache/server.php');
		$this->server = $server;
	}

	/**
	 * 缩略附件图片
	 *
	 * @param string $oldimg
	 * @param string $newimg
	 * @param integer $picwidth
	 * @param integer $picheight
	 * @param integer $quality
	 * @return unknown
	 */
	protected function resize_image($oldimg='', $newimg='', $picwidth=0, $picheight=0, $quality=80)
	{ //缩略附件图片
		$picwidth==0 && $picwidth = $this->picwidth;
		$picheight==0 && $picheight = $this->picheight;

		if ( !trim($oldimg) || !trim($newimg) )
		return 0;
		if ( !is_file($oldimg))
		return 0;
		if ( !$picwidth && !$picheight )
		return 0;
		if ( $picwidth < 0 || $picheight < 0 )
		return 0;
		if ( $quality < 1 )
		return 0;
		// Get the extend name of the old file
		$filename = $oldimg;
		if ( strstr($oldimg, "/")){
			$filename = end(explode("/", $oldimg));
		}
		if (!strstr($filename, ".")){
			return 0;
		}
		$extname = end(explode(".", $filename));
		$extname = strtolower($extname);

		//检验新文件
		$filename = $newimg;
		if ( strstr($newimg, "/"))
		{
			$filename = end(explode("/", $newimg));
		}
		if ( !strstr($filename, ".")){
			return 0;
		}
		$nextname = end(explode(".", $filename));
		$nextname = strtolower($nextname);
		//文件检验完毕
		// Select the format of the new image
		switch ( $extname )
		{
			case "jpg"    : $im = imagecreatefromjpeg($oldimg); break;
			case "jpeg"    : $im = imagecreatefromjpeg($oldimg); break;
			case "gif"    : $im = imagecreatefromgif($oldimg); break;
			case "png"    : $im = imagecreatefrompng($oldimg); break;
			default        : return 0; break;
		}

		$color = imagecolorallocate($im, 255, 255, 255);
		$filesize = getimagesize($oldimg);

		if ( $picwidth && !$picheight ){
			$picheight = $filesize[1]*$picwidth/$filesize[0];
		}else if ( !$picwidth && $picheight ){
			$picwidth = $filesize[0]*$picheight/$filesize[1];
		}

		$p = ($picwidth/$picheight);
		if($filesize[0]/$filesize[1] > $p){ //说明宽度太大，则以宽为标准
			$newwidth = $picwidth;
			$newheight = $filesize[1] * ($picwidth/$filesize[0]);
			//$newheight = $filesize[1];
			//$newwidth = $newheight*$p;
		}else{	//否则，以高为标准
			$newheight = $picheight;
			$newwidth = $filesize[0] * ($picheight/$filesize[1]);
			//$newwidth = $filesize[0];
			//$newheight = $newwidth/$p;
		}

		$output = imagecreatetruecolor($newwidth, $newheight);
		imagecopyresampled($output, $im, 0, 0, 0, 0, $newwidth, $newheight, $filesize[0], $filesize[1]);
		switch ( $nextname )
		{
			case "jpg" :
				$result = imagejpeg($output, $newimg , $quality);
				break;
			case "jpeg":
				$result = imagejpeg($output, $newimg , $quality);
				break;
			case "gif" :
				$result = imagegif($output, $newimg);
				break;
			case "png" :
				$result = imagepng($output, $newimg);
				break;
			default    :
				$result = 0;
				break;
		}
		imagedestroy($output);
		if ( $result ){
			return 1;
		}else{
			return 0;
		}
	}

	/**
	 * 获取数码照片的EXIF信息
	 *
	 * @param string $filepath
	 * @return array
	 */
	protected function getFileExif($filepath)
	{
		if (!function_exists('exif_read_data'))
		{
			return ;
		}
		$exifInfo = exif_read_data($filepath);

		$del = array('FileDateTime', 'MakerNote', 'FileName', 'FileDateTime', 'MimeType', 'FileType', 'FileSize', 'SectionsFound', 'ComponentsConfiguration', 'FileSource', 'UserComment');
		$first = array('Make', 'Model', 'ApertureValue', 'FocalLength', 'DateTime');
		$second = array('Flash', 'ExposureBiasValue');

		$exif = array(
		'Make' => '制造',
		'Model' => '型号',
		'DateTime' => '拍摄时间',
		'ExposureTime' => '快门',
		'FNumber' => '光圈系数',
		'ApertureValue' => '',
		);
		$newInfo = array();
		
		foreach ($exifInfo as $key => $val)
		{
			//$val = mb_convert_encoding($val, 'utf-8');
			if (empty($val))
			{
				continue;
			}
			elseif (strpos($key, 'UndefinedTag') === 0)
			{
				continue;
			}
			elseif (in_array($key, $del))
			{
				continue;
			}
			elseif (is_array($val))
			{
				continue;
			}
			elseif (in_array($key, $first))
			{
				$newInfo[1][$key] = $val;
			}
			elseif (in_array($key, $second))
			{
				$newInfo[2][$key] = $val;
			}
			else
			{
				$newInfo[3][$key] = $val;
			}
		}
		return $newInfo;
	}

	/**
	 * 截取视频截图
	 *
	 * @param string $filepath 视频文件路径
	 * @return boolean 截取是否成功
	 */
	protected function videoScreen($filepath)
	{
		if (!extension_loaded('ffmpeg')) { //未能加载FFmpeg模块
			return false;
		}
		$movie = new ffmpeg_movie($filepath);

		if (!$movie->getVideoCodec())
		{
			return false;
		}
		$framenum = $movie->getFrameCount();
		$frameId = rand(0, $framenum);
		$ff_frame = $movie->getFrame($frameId);
		if (!is_object($ff_frame) || !method_exists($ff_frame, 'toGDimage'))
		{
			return false; //说明获取失败
		}
		$gdimage = $ff_frame->toGDimage();

		$height = $movie->getFrameHeight();
		$width = $movie->getFrameWidth();

		/* 视频文件截图的生成原则是在原目录下生成同名不同后缀的文件 */
		$imagepath = $this->getFramePic($filepath);

		if ($gdimage)
		{
			imagepng($gdimage, $imagepath);
			imagedestroy($gdimage);
			// 如果大于尺寸，则需要进行缩略
			if ($height > 500 || $width > 500)
			{
				$this->resize_image($imagepath, $imagepath, 500, 500);
			}
			$videoInfo = array();

			$videoInfo['rate'] = round($movie->getframerate()); //码流
			$videoInfo['videocodec'] = $movie->getvideocodec(); //视频编码
			$videoInfo['audiocodec'] = $movie->getaudiocodec(); //音频编码
			$videoInfo['frameheight'] = $movie->getframeheight(); //画面帧高度
			$videoInfo['framewidth'] = $movie->getframewidth(); //画面帧宽度
			//print_r($videoInfo);
			return $videoInfo;
		}
		return false;
	}

	/**
	 * 格式化视频信息
	 *
	 * @param unknown_type $info
	 * @return unknown
	 */
	protected function getVideoInfo($info)
	{
		$v = array(
		'rate' => '码流',
		'videocodec' => '视频编码',
		'audiocodec' => '音频编码',
		'frameheight' => '视频画面高度',
		'framewidth' => '视频画面宽度',
		);
		foreach ($info as $key => $val)
		{
			$newInfo[$v[$key]] = $val;
		}
		return $newInfo;
	}

	/**
	 * 文件保存目录，根据系统设置分目录规则获取分目录，并且检查目录
	 *
	 * @return string
	 */
	protected function saveDir($path)
	{
		global $very;

		switch($very['attachmkdir'])
		{
			case 1: $savedir = ''; break;
			case 2: $savedir = $file_ext; break;
			case 3: $savedir = date('Ym'); break;
			case 4: $savedir = date('Ym/d'); break;
			default:$savedir = date('Ym/d'); break;
		}

		if (is_dir($path . '/' . $savedir))
		{
			return $savedir;
		}
		$dirs = explode('/', $savedir);
		$dirpath = '';
		while ($directory = array_shift($dirs)) {
			$dirpath .='/'.$directory;
			if(!is_dir($path . $dirpath))
			{
				mkdir($path . $dirpath);
				if(!chmod($path . $dirpath, 0777))
				{
					showAlert('pub_mkdirfail');
				}
			}
		}

		//echo $savedir;
		return $savedir; //返回路径
	}

	/**
	 * 上传文件
	 *
	 * @param string $tmp_name
	 * @param string $filename
	 * @return boolean
	 */
	protected function postupload($tmp_name,$filename)
	{
		if(strpos($filename,'..')!==false || eregi("\.php$",$filename)){
			exit('illegal file type!');
		}
		if(function_exists("move_uploaded_file") && @move_uploaded_file($tmp_name,$filename)){
			@chmod($filename,0777);
			return true;
		}elseif(@copy($tmp_name, $filename)){
			@chmod($filename,0777);
			return true;
		}elseif(is_readable($tmp_name)){
			writeover($filename,readover($tmp_name));
			if(file_exists($filename)){
				@chmod($filename,0777);
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断文件是否上传得到
	 *
	 * @param unknown_type $tmp_name
	 * @return unknown
	 */
	protected function if_uploaded_file($tmp_name)
	{
		if(!$tmp_name || $tmp_name=='none'){
			return false;
		}elseif(function_exists('is_uploaded_file') && !is_uploaded_file($tmp_name) && !is_uploaded_file(str_replace('\\\\', '\\', $tmp_name))){
			return false;
		}else{
			return true;
		}
	}

	/**
	 * 获取其预览URL
	 *
	 * @param string $type
	 * @param string $path
	 * @return string
	 */
	protected function getPreviewUrl($type, $path)
	{
		$type = strtolower($type);
		if (in_array($type, $this->imgExt))
		{
			return "javascript:showpic('$path');";
		}
		elseif (in_array($type, $this->wmpExt))
		{
			return "javascript:showwmp('$path');";
		}
		elseif (in_array($type, $this->rmExt))
		{
			return "javascript:showrm('$path');";
		}
		else
		{
			return 'javascript:void(0);';
		}
	}

	/**
	 * 格式化文件大小
	 *
	 * @param float $size
	 * @return float
	 */
	protected function getFileSize($size)
	{
		if ($size > 1000000000)
		{
			$newsize = round($size/1000000000,2);
			$newsize .= ' GB';
		}
		elseif ($size > 1000000)
		{
			$newsize = round($size/1000000,2);
			$newsize .= ' MB';
		}
		elseif ($size > 1000)
		{
			$newsize = round($size/1000, 1);
			$newsize .= ' KB';
		}
		else 
		{
			$newsize = $size . ' Byte';
		}
		return $newsize;
	}

	/**
	 * 根据文件名来构造其两个缩略图文件名
	 *
	 * @param string $filepath
	 * @return array
	 */
	protected function getSmallPic($filepath)
	{
		$fileext = end(explode('.', $filepath));
		$filename = substr($filepath, 0, -(strlen($fileext) + 1));
		return array($filename . '_s1.' . $fileext, $filename . '_s2.' . $fileext, );
	}

	/**
	 * 获取帧截图
	 *
	 * @param string $url
	 */
	protected function getFramePic($url, $type = 0)
	{
		if ($type) {
			return  str_replace('.' . end(explode('.', $url)), "_$type.jpg", $url);
		} else {
			return str_replace('.' . end(explode('.', $url)), '.jpg', $url);
		}
	}
	
	protected function getFlv($url)
	{
		return str_replace('.' . end(explode('.', $url)), '.flv', $url);
	}
	
	static function checkDir($path)
	{
		if(is_dir($path)) 
		{
			return ;
		}
		$pathInfo = pathinfo($path);
		$path = $pathInfo['dirname'];
		$dirs = explode('/',$path);
		$dirpath = '';
		if (strpos($path, '/') !== 0) //Windows系统 或者是相对目录
		{
			$isWindows = 1;
		}
		$depth = 0;
		while ($directory = array_shift($dirs)) 
		{
			if ($depth == 0 && $isWindows)
			{
				$dirpath = $directory;
			}
			else 
			{
				$dirpath .= '/' . $directory;
			}
			$depth++;
			if (!is_dir($dirpath))
			{
				mkdir($dirpath);
				if (!chmod($dirpath,0777))
				{
					showalert('pub_mkdirfail');
				}
			}
		}
	}
	
	protected function delete($rid)
	{
		if (is_array($rid)) {
			$sql = 'rid IN(' . implode(',', $rid) . ') ';
		} else {
			$sql = 'rid = ' . intval($rid);
		}
		global $db;
		$rs = $db->query("SELECT filepath,serverid,type,ifconvert FROM cms_resource WHERE $sql");
		while ($d = $db->fetch_array($rs)) {
			$filepath = $this->server[$d['serverid']]['serverpath'] . $d['filepath'];
			if (in_array($d['type'], $this->imgExt)) {
				list($img1, $img2) = $this->getSmallPic($filepath);
				unlink($img1);
				unlink($img2);
			} elseif ($d['ifconvert'])
			{
				$img0 = $this->getFramePic($filepath);
				$img1 = $this->getFramePic($filepath, 1);
				$img2 = $this->getFramePic($filepath, 2);
				$flv = $this->getFlv($filepath);
				unlink($img0);
				unlink($img1);
				unlink($img2);
				unlink($flv);
			}
			unlink($filepath);
		}
	}

}
?>